<?php

namespace app\api\controller\v2;

use EasyWeChat\Factory;
use app\common\model\WxpayV2;
use think\facade\Log;
use think\facade\Db;
use think\Request;

/**
 * 支付
 */
class Pay extends \app\BaseController
{


    protected $middleware = [
        \app\middleware\ApiUserAuthV2::class => ['except' => ['wechatH5']],
    ];

    /**
     * 订单类型
     */
    private $orderTypeMap = [
        'mobile', // 话费
        'movie', // 影票
        'coupon', // 权益卡
    ];

    private $error = null;

    /**
     * 创建支付
     */
    private function getPayParams()
    {
        $orderId = input('order_id');
        if (empty($orderId)) {
            $this->error = '订单号不能为空';
            return false;
        }
        $orderType = input('order_type');
        if (empty($orderType)) {
            $this->error = '订单类型不能为空';
            return false;
        }
        if (!in_array($orderType, $this->orderTypeMap)) {
            $this->error = '订单类型有误';
            return false;
        }

        $order = Db::name($orderType . '_order')
            ->where('order_id', $orderId)
            ->find();
        if (empty($order)) {
            $this->error = '订单不存在';
            return false;
        }
        if ($order['status'] != 1 && $orderType != 'coupon') {
            $this->error = '订单当前状态无法支付：' . $order['status'];
            return false;
        }
        if ($order['status'] != 0 && $orderType == 'coupon') {
            $this->error = '订单当前状态无法支付：' . $order['status'];
            return false;
        }
        switch ($orderType) {
            case 'mobile':
                $price = $order['sale_price'];
                $body = '话费充值 ' . fen2yuan($order['amount']) . ' 元';
                $payLogTable = 'pay_log';
                break;
            case 'movie':
                $price = $order['sale_price'];
                $body = '购买影票 ' . $order['film_name'];
                $payLogTable = 'movie_pay_log';
                break;
            case 'coupon':
                $body = '购买权益卡';
                $payLogTable = 'coupon_pay_log';
                $price = $order['pay_amount'];
                break;
            default:
                $this->error = '订单类型有误';
                return false;
        }

        if ($order['settle_type'] == SETTLE_TYPE_PROFIT) {
            $agentId = 0;
        } else {
            $agentId = $order['agent_id'];
        }

        return [
            'agent_id' => $agentId,
            'body' => $body,
            'order_id' => $orderId,
            'sale_price' => $price,
            'product' => $orderType,
            'pay_log_table' => $payLogTable,
        ];
    }

    /**
     * 微信 H5 支付
     */
    public function wechatH5(Request $request)
    {
        $params = $this->getPayParams();
        if (false === $params) {
            return fail($this->error);
        }

        try {
            $pay = new WxpayV2($params['agent_id'], 'wechat_mweb', $params['product']);
            $res = $pay->create([
                'body' => $params['body'],
                'out_trade_no' => $params['order_id'],
                'total_fee' => $params['sale_price'],
                // 'total_fee' => 1, // 测试 1 分钱
                'spbill_create_ip' => $request->ip(),
                'trade_type' => 'MWEB',
            ]);
            Db::name($params['pay_log_table'])
                ->where('order_id', $params['order_id'])
                ->update([
                    'trade_type' => 'MWEB'
                ]);
            if (!isset($res['return_code']) || $res['return_code'] != 'SUCCESS') {
                Log::write($res, 'error');
                return fail($res['return_msg'] ?? '支付订单生成失败，请稍后再试。');
            }
            if (!isset($res['result_code']) || $res['result_code'] != 'SUCCESS') {
                Log::write($res, 'error');
                return fail($res['err_code_des'] ?? '支付订单生成失败，请稍后再试！');
            }


            // 支付成功后的跳转地址
            $redirectUrl = getRedirectUrl();

            // backIndex=1 前端用来判断返回页面，防止重复唤起微信支付
            $redirectUrl = '&redirect_url=' . $redirectUrl;

            $is_kuaizhan = input('is_kuaizhan',0);

            if ($is_kuaizhan){
                $mweb_url = $res['mweb_url'].$redirectUrl;
                echo "<script language='javascript' type='text/javascript'>window.location.href='$mweb_url'</script>";

            }else{
                return success('操作成功', [
                    'mweb_url' => $res['mweb_url'] . $redirectUrl,
                ]);
            }

        } catch (\Exception $e) {
            return fail('微信 H5 支付配置有误：' . $e->getMessage() . $e->getLine());
        }
    }


    /**
     * 快站的h5支付
     */
    public function wechatH5ByKuaizhan(Request $request){

    }

    /**
     * 微信 JSAPI 支付
     */
    public function wechatJsapi(Request $request)
    {
        $params = $this->getPayParams();
        if (false === $params) {
            return fail($this->error);
        }

        try {
            $pay = new WxpayV2($params['agent_id'], 'wechat', $params['product']);
            $res = $pay->create([
                'body' => $params['body'],
                'out_trade_no' => $params['order_id'],
                'total_fee' => $params['sale_price'],
                // 'total_fee' => 1, // 测试 1 分钱
                'spbill_create_ip' => $request->ip(),
                'trade_type' => 'JSAPI',
                'openid' => $request->user['openid'],
            ]);
            if (!isset($res['return_code']) || $res['return_code'] != 'SUCCESS') {
                Log::write($res, 'error');
                return fail($res['return_msg'] ?? '支付订单生成失败，请稍后再试。');
            }
            if (!isset($res['result_code']) || $res['result_code'] != 'SUCCESS') {
                Log::write($res, 'error');
                return fail($res['err_code_des'] ?? '支付订单生成失败，请稍后再试！');
            }
            $payment = $pay->jssdk($res['prepay_id']);
            Db::name($params['pay_log_table'])
                ->where('order_id', $params['order_id'])
                ->update([
                    'trade_type' => 'JSAPI'
                ]);

            return success('操作成功', $payment);
        } catch (\Exception $e) {
            return fail('微信公众号支付配置有误：' . $e->getMessage());
        }
    }
}
